#include <fcntl.h>
#include <sys/stat.h>

#include <sys/sendfile.h>
#include <iostream>

#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>

#include <cerrno>
#include <cstring>
#include <cstdlib>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, char *argv[])
{
        // Creates new socket
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) {
                std::cerr << "Error opening socket" << std::endl;
                return 1;
        }

        sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
	inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);
        int portno = 6666;
        serv_addr.sin_port = htons(portno);

        if(connect(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
                std::cerr << "ERROR connecting" << std::endl;
                return 1;
        }
	std::cout << "connected to server\n";

	int fd_out = creat("recieve",O_RDWR);
	
	int n = 0;
	int k = 0;
	const int SIZE = 1024;
	char buffer[SIZE];
	while(n = read(sockfd, buffer,SIZE))
	{
		//std::cout << ".";
		write(fd_out, buffer, n);
	}

	//int kkk = splice(sockfd, NULL, fd_out, NULL, 189, 0);
	//std::cout << kkk << std::endl;
        close(sockfd);
        close(fd_out);
        return 0;
}
